package config

import (
	"github.com/spf13/viper"
	//"integral_api/utils/logs"
	"log"
	"os"
)

var cfgDatabase *viper.Viper
var cfgApplication *viper.Viper
var cfgRedisConn *viper.Viper
var cfgRabbitMqConn *viper.Viper

/**
	合并配置项
	1、AddConfigPath 2、SetConfigName 3、SetConfigType("yaml")
	4、MergeInConfig()	5、ReadInConfig()
 */
func init() {
	//判断引入配置文件路径
	if len(os.Args) > 1 {
		if os.Args[1] == "test" {
			viper.AddConfigPath("config/test")
		} else if os.Args[1] == "dev" {
			viper.AddConfigPath("config/dev")
		} else if os.Args[1] == "pre" {
			viper.AddConfigPath("config/pre")
		} else if os.Args[1] == "prod" {
			viper.AddConfigPath("config/prod")
		}
	} else {
		viper.AddConfigPath("config/dev")
	}
	//设置主配置文件
	viper.SetConfigName("main") // name of config file (without extension)
	//viper.AddConfigPath("./config") // optionally look for config in the working directory
	//合并配置
	err := viper.MergeInConfig()
	if err != nil {
		log.Println(err) // Handle errors reading the config file
	}
	//读取配置
	err = viper.ReadInConfig() // Find and read the config file
	if err != nil {
		log.Println(err) // Handle errors reading the config file
	}
	//设置params配置
	viper.SetConfigName("params")
	err = viper.MergeInConfig()
	if err != nil {
		log.Println(err) // Handle errors reading the config file
	}

	//设置common配置
	viper.AddConfigPath("config")
	viper.SetConfigName("common")
	err = viper.MergeInConfig()
	if err != nil {
		log.Println(err) // Handle errors reading the config file
	}
	//引入数据库配置文件信息
	cfgDatabase = viper.Sub("settings.database")
	if cfgDatabase == nil {
		panic("config not found settings.database")
	}
	//配置数据库信息
	DatabaseConfig = InitDatabase(cfgDatabase)

	//配置application配置
	cfgApplication = viper.Sub("settings.application")
	if cfgApplication == nil {
		panic("config not found settings.application")
	}
	ApplicationConfig = InitApplication(cfgApplication)

	//引入redis配置文件信息
	cfgRedisConn = viper.Sub("settings.redis")
	if cfgRedisConn == nil {
		panic("config not found settings.redis")
	}
	RedisConfig = InitRedis(cfgRedisConn)

	//配置rabbitMq
	cfgRabbitMqConn = viper.Sub("settings.rabbitMq")
	if cfgRabbitMqConn == nil {
		panic("config not found settings.rabbitmq")
	}
	RabbitMqConf = InitRabbitMqConn(cfgRabbitMqConn)

	//_ = logs.InitDailyLog("debug", "logs/")
}

func SetApplicationIsInit() {
	viper.AddConfigPath("./config")
	viper.Set("settings.application.isInit", false)
	viper.WriteConfig()
}
